package com.chen.auth.service.impl;


import com.chen.auth.feign.RemoteSysUserService;
import com.chen.auth.service.AuthUserService;
import com.chen.root.enums.AccountEnums;
import com.chen.root.oclass.dto.UserInfoDTO;
import com.chen.root.oclass.vo.LoginVO;
import com.chen.common.security.info.UserInfo;
import com.chen.common.security.utils.HttpServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ~龙~
 */
@Slf4j
@Service
public class AuthUserServiceImpl implements AuthUserService {

    @Resource
    HttpServletRequest httpServletRequest;
    @Resource
    RemoteSysUserService remoteSysUserService;

    @Override
    public UserDetails loadUserByPhone(String phone) throws UsernameNotFoundException {
        Map<String, String> parameterMap = HttpServletUtils.paramMap(httpServletRequest);
        // 远程调用user模块查询用户信息
        String accountType = parameterMap.get("accountType");
        LoginVO params = new LoginVO().setPhone(phone).setAccountType(accountType);
        UserInfoDTO info = remoteSysUserService.userInfoByPhone(params).getData();

        return buildUserInfo(info,accountType);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Map<String, String> parameterMap = HttpServletUtils.paramMap(httpServletRequest);
        // 远程调用user模块查询用户信息
        String accountType = parameterMap.get("accountType");
        LoginVO params = new LoginVO().setUsername(username).setAccountType(accountType);
        UserInfoDTO info = remoteSysUserService.userInfo(params).getData();

        return buildUserInfo(info,accountType);
    }

    private UserInfo buildUserInfo(UserInfoDTO info,String accountType){
        if (info == null) {
            throw new UsernameNotFoundException("用户账号不存在，请确认用户账号是否正确！");
        }

        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String authoritiesStr : info.getAuthoritiesList()) {
            authorities.add(new SimpleGrantedAuthority(authoritiesStr));
        }

        return new UserInfo(
                info.getUserId(), info.getPhone(),
                info.getUsername(), info.getPassword(),
                AccountEnums.normal.getValue().equals(info.getEnabled()),
                true,
                true,
                true,
                authorities, accountType
        );
    }

}